/**
 * This file is part of AppStoreBot.
 *
 *  AppStoreBot is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AppStoreBot is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AppStoreBot.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package lu.pragmaconsult.appstorebot.itunes;


import lu.pragmaconsult.appstorebot.BotContext;
import lu.pragmaconsult.appstorebot.ExitStatus;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;

/**
 * TODO: Type comment
 * @author Wilfried Vandenberghe (wilfried.vandenberghe at pragmaconsult.lu)
 */
abstract class AbstractBotState implements BotState {

	private static final HttpClient httpClient = new HttpClient();
	private static ITunesConnectBot bot;
	
	static final void setBot(ITunesConnectBot aBot) {
		bot = aBot;
	}
	
	static final ITunesConnectBot getBot() {
		return bot;
	}
	
	static final HttpClient getHttpClient() {
		return httpClient;
	}

	/* (non-Javadoc)
	 * @see lu.pragmaconsult.appstorebot.itunes.BotState#run()
	 */
	@Override
	public ExitStatus run() {
		HttpMethod method = createHttpMethod(bot.getBotContext(), httpClient);
		
		try {
			if(method != null) {
				httpClient.executeMethod(method);
			}
			
			processResponseBody(bot.getBotContext(), method);
		} catch (Exception e) {
			return ExitStatus.FAILURE;
		} finally {
			if(method != null) {
				method.releaseConnection();
			}
		}
		
		BotState state = getNextState();
		if(state != null) {
			bot.setState(state);
			return bot.run();
		}
		
		return ExitStatus.COMPLETE;
	}
	
	/**
	 * 
	 * @param context
	 * @return
	 */
	protected abstract HttpMethod createHttpMethod(BotContext context, HttpClient httpClient);
	
	/**
	 * 
	 * @param context
	 * @param method
	 */
	protected abstract void processResponseBody(BotContext context, HttpMethod method);
	
	/**
	 * 
	 * @return
	 */
	protected abstract BotState getNextState();
}
